<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增用户 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="createActions(record)"
          />
        </template>
      </template>
    </BasicTable>
    <UserDrawer @register="registerUserDrawer" @success="handleSuccess" />
    <ResetPasswordDrawer @register="registerResetPasswordDrawer" @success="handleSuccess" />
  </div>
</template>

<script lang="tsx" setup>
  import { BasicTable, useTable, TableAction, ActionItem, FormSchema } from '@/components/Table';
  import { getUserList } from '@/api/user';
  import { useDrawer } from '@/components/Drawer';
  import UserDrawer from './UserDrawer.vue';
  import ResetPasswordDrawer from './ResetPasswordDrawer.vue';

  const columns: BasicColumn[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      width: 150,
    },
    {
      title: '账号',
      dataIndex: 'username',
      width: 60,
    },
    {
      title: '角色',
      dataIndex: 'roles',
      width: 60,
      customRender: ({ record }) => {
        return record.roles.map(item => item.name).join(' ');
      },
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '姓名',
      component: 'Input',
      colProps: { span: 8 },
    },
  ];

  const [registerTable, { reload }] = useTable({
    title: '用户管理',
    api: getUserList,
    columns,
    formConfig: {
      labelWidth: 50,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: true,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
    },
  });

  const createActions = (record) => {
    const actions: ActionItem[] = [
      {
        label: '编辑',
        onClick: () => {
          handleEdit(record)
        },
      },
      {
        label: '重置密码',
        onClick: () => {
          handleResetPassword(record)
        },
      },
    ];
    return actions;
  };

  const [registerUserDrawer, { openDrawer: openUserDrawer }] = useDrawer();
  const [registerResetPasswordDrawer, { openDrawer: openResetPasswordDrawer }] = useDrawer();

  function handleCreate() {
    openUserDrawer(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openUserDrawer(true, {
      record,
      isUpdate: true,
    });
  }

  function handleResetPassword(record: Recordable) {
    openResetPasswordDrawer(true, {
      record,
    });
  }

  function handleSuccess() {
    reload();
  }

</script>